import { rollup } from "rollup";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import DefineOptions from "unplugin-vue-define-options/rollup";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import esbuild from "rollup-plugin-esbuild";
import glob from "fast-glob";
import { mainRoot, pkgRoot } from "../utils/paths";
import { excludeFiles, generateExternal, writeBundles } from "../utils";
import { pathAlias } from "../plugins/path-alias";
import { buildConfigEntries, target } from "../utils/config";
import type { OutputOptions } from "rollup";
import postcss from "rollup-plugin-postcss";
export const buildModules = async () => {
  const input = excludeFiles(
    await glob("**/*.{js,ts,vue,tsx,jsx}", {
      cwd: pkgRoot,
      absolute: true,
      onlyFiles: true,
    })
  );
  const bundle = await rollup({
    onwarn: function (warning) {
      // Skip certain warnings

      // should intercept ... but doesn't in some rollup versions
      if (warning.code === "THIS_IS_UNDEFINED") {
        return;
      }

      // console.warn everything else
      console.warn(warning.message);
    },
    input,
    plugins: [
      pathAlias(),
      DefineOptions(),
      vue({
        isProduction: false,
      }),
      vueJsx(),
      postcss({
        use: {
          less: {
            javascriptEnabled: true,
          },
          sass: {
            javascriptEnabled: true,
          },
          stylus: null,
        },
      }),
      nodeResolve({
        extensions: [".mjs", ".js", ".json", ".ts"],
      }),
      commonjs(),
      esbuild({
        sourceMap: false,
        target,
        loaders: {
          ".vue": "ts",
        },
      }),
    ],
    external: await generateExternal({ full: false }),
    treeshake: false,
  });
  await writeBundles(
    bundle,
    buildConfigEntries.map(([module, config]): OutputOptions => {
      return {
        format: config.format,
        dir: config.output.path,
        exports: module === "cjs" ? "named" : undefined,
        preserveModules: true,
        preserveModulesRoot: pkgRoot,
        sourcemap: false,
        entryFileNames: `[name].${config.ext}`,
      };
    })
  );
};
